#include "BladerSpawner.h"
#include "..\Generic\Random.h"
#include "..\Graphics\Camera.h"
#include "..\Managers\RenderManager.h"
#include <algorithm>
#include "BladerFactory.h"
#include "..\Components\GameObject.h"
#include "..\Managers\GameObjectManager.h"
#include "..\Components\PhysicsComponent.h"

BladerSpawner::BladerSpawner(GameObjectManager* p_gameObjectManager, int p_minSpawn, int p_maxSpawn) : m_gameObjectManager(p_gameObjectManager), m_minSpawn(p_minSpawn), m_maxSpawn(p_maxSpawn){}
BladerSpawner::~BladerSpawner(void){}

void BladerSpawner::update(const GameTime& p_gameTime)
{
	m_elapsedTime = std::min(m_elapsedTime + p_gameTime.getElapsedTimeAsMilliseconds(), m_targetTime);
	if (m_elapsedTime >= m_targetTime)
	{
		spawn();
	}
}

inline void BladerSpawner::spawn()
{
	vn::FloatRect rect = RenderManager::getSingleton().getRenderEngine()->getCamera("main")->getBoundary();
	BladerFactory bladerFactory;
	float x, y, direction;
	int spawnPoint = vn::Random::getValue(1, 2);
	if (spawnPoint == 1)
	{
		x = rect.x;
		y = vn::Random::getValue(rect.y, rect.y + rect.h);
		direction = 1.0f;
	}
	else
	{
		x = rect.x + rect.w;
		y = vn::Random::getValue(rect.y, rect.y + rect.h);
		direction = -1.0f;
	}
	GameObject* blader = bladerFactory.createEnemy(vn::Vector2(x, y), "player");
	blader->setGameObjectManager(m_gameObjectManager);
	static_cast<PhysicsComponent*>(blader->getComponent("PhysicsComponent"))->getBody()->SetLinearVelocity(b2Vec2(2.0f * direction, 0.0f));
	m_gameObjectManager->addGameObject(blader);
	generateTime();
}

inline void BladerSpawner::generateTime()
{
	m_targetTime = vn::Random::getValue(m_minSpawn, m_maxSpawn);
	m_elapsedTime = 0;
}